#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import time
from net.core.request import request
from net.protocol.cmd import command

packet=lambda cmd,content:command().packet(cmd,content)
unpacket=lambda buff:command().unpacket(buff)

class process(request):
    def __init__(self,connection,address,id,s_clients):
        super(process,self).__init__(connection,address,id,s_clients)
        self.__name = None
    def run(self):
        try:
            buff=bytearray()
            while self._runing.is_set():
                self._flag.wait()
                recv=self._connect.recv(1024)
                buff.extend(recv)
                if len(recv)>0:
                    if recv[len(recv)-1]==0x00:
                        self.cmd(command().unpacket(buff))
                        buff.clear()
                self._flag.set()        
                continue
        except Exception as e:
            self.close()
            print("Server - %s" %e)
        finally:
            print("Server - close")
            self._connect.shutdown(2)
            self._connect.close()
    
    def cmd(self,command):
        if command.cmd.lower() == "join":
            self.joinnetwork(command.content.lower())
        if command.cmd.lower() == "status":
            self.setStatus(command.content.lower())
        if command.cmd.lower() == "exit":
            self.exit(command.content.lower())
        if command.cmd.lower() == "complete":
            self.complete()
        if command.cmd.lower() == "heartpackage":
            self.heartpackage()

    def heartpackage(self):
        pass

    def complete(self):
        if self.__name:
            self._status[self.__name] = "free"

    def exit(self,content):
        '''
        exit process and dispose all resource
        '''
        if self.__name in self._clients:
            self._connect.shutdown(2)
            self._connect.close()
            del self._clients[self.__name] #删除对象
            del self._status[self.__name]  #删除状态
            print("Server - %s - %s is closed!\r\n" % (time.localtime,self.__name))
            if content:
                '''
                    has an work not complete,to do some things
                '''
                print("Server - has an work is not complete %s\r\n" % content)
                pass

    def setStatus(self,status):
        self._status[self.__name]=status
        print("Server - [%s] %s's status is chanage:%s\r\n" % (time.localtime,self.__name,status))

    def response(self,cmd,content):
        try:
            self._connect.send(command().packet(cmd,content))
        except Exception as e:
            print("Server - has a Error (%s)" % e)

    def workNotify(self,url):
        if self._status[self.__name] == "free":
            self.clients[self.__name]._connect.send(command().packet("work",url))
            self._status[self.__name]="lock" #wait client callback status
        print("Server - Notify %s work send to %s"%(url,self.__name))

    def joinnetwork(self,name):
        if name not in self._clients:
            self.__name=name
            self._clients[self.__name]=self._connect
            self._status[self.__name]="free"
            print("Server - [%s] %s new jobNode connected\r\n %s name:%s" % (time.localtime,str(self._address),bytearray([0x09]).decode("utf-8"),name))
            self.response("online",str(time.localtime))
        else:
            print("Server - has a error %s this node has join,please checked!" % (time.localtime))
            self.response("Server - has a error %s this node has join,please checked!" % (time.localtime))